package com.lzh.controller;


import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;


@Controller
public class UploadController {

    /*
    * 在形参上使用@RequestParam("file") MultipartFile multipartfile 接收上传文件的时候
    *   @RequestParam("file")中的file就是form表单中input中文件的name属性值
    *
    */
    @RequestMapping("uploadfile")
    public String uploadFile(HttpServletRequest request,@RequestParam("file") MultipartFile multipartfile ){

      /* 等同于@RequestParam
        //得到文件上传的request对象
        MultipartHttpServletRequest multipart = (MultipartHttpServletRequest) request;
        //得到上传的文件
        MultipartFile multipartfile = multipart.getFile("file");
        */
        //判断上传文件是否为空
        if(multipartfile.isEmpty()){
            request.setAttribute("msg","请选择你要上传的文件！");
            return "result";
        }
        System.out.println("1");
        save(multipartfile,request);
        System.out.println("last");
        return "result";
    }

    /*
    *   多文件上传
    *

    @RequestMapping("uploadfiles")
    public String uploadFiles(HttpServletRequest request,@RequestParam("files") List<MultipartFile> multipartfiles ){

        //判断上传文件是否为空,而且长度大于0
        if(multipartfiles.isEmpty() && multipartfiles.size() > 0){
            //遍历集合
            for (MultipartFile multipartFile : multipartfiles){
                if(multipartFile.isEmpty()){
                    request.setAttribute("msg","请选择你要上传的文件！");
                    return "result";
                }
                save(multipartFile,request);
            }

        }

        return "result";
    }*/

    /*
        保存文件
    */
    public void save(MultipartFile multipartfile, HttpServletRequest request){
        //得到上传文件名
        String  OriginalFilename = multipartfile.getOriginalFilename();
        //截取文件名，获取文件后缀
        String siffx = OriginalFilename.substring(OriginalFilename.lastIndexOf("."));
        //生成随机文件名字
        String fileName = System.currentTimeMillis()+ siffx;
        //得到项目真实路径
        //getServletContext()这个方法只有Selvet3.0才有
        String realPath = request.getServletContext().getRealPath("/");
        //设置文件存放路径
        File filePath = new File(realPath+"/upload1");
        System.out.println(filePath);
        //判断存放文件目录是否存在，如果不存在则生成一个
        if(!filePath.exists()){
            filePath.mkdirs();
        }
        try {
            //上传文件
            multipartfile.transferTo(new File(filePath,fileName));
            request.setAttribute("msg","文件上传成功！");
        } catch (IOException e) {
            request.setAttribute("msg","文件上传失败!");
            e.printStackTrace();
        }
    }
}
